<template>
	<div class="create-comment">
		<router-link :to="`/userhomepage/${userinfo.userinfo.user_id}`"> <el-avatar shape="square" :src="`${ENV.VITE_BASE_URL}${userinfo.userinfo.avatar}`" /> </router-link>
		<div class="main">
			<el-input v-model="text" resize="none" :maxlength="200" :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" />
			<el-button type="primary" @click="submit" :loading="btnLoading">发布</el-button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { createComment } from "@/api/comment";
import { useUserinfoStore } from "@/stores/userinfo";
import { error } from "@/util/ElMessage";
import { inject, ref, type Ref } from "vue";
const userinfo = useUserinfoStore();
const ENV = import.meta.env;
const text = ref("");
const blogItem: blogItemType | undefined = inject("blogItem");

const {
	userinfo: { avatar, nickName, user_id }
} = useUserinfoStore();
const commentList: Ref<commentItemType[]> | undefined = inject("commentList");
const btnLoading = ref(false);

const submit = async () => {
	btnLoading.value = true;

	try {
		const {
			data: { data }
		} = await createComment(blogItem!.blog_id, text.value);

		commentList!.value.unshift({ content: text.value, createdAt: new Date(), thumb_up: 0, comment_id: data.comment_id, user: { avatar, nickName, user_id } });
		text.value = "";
	} catch (err) {
		console.log(err);

		error("发布失败");
	} finally {
		btnLoading.value = false;
	}
};
</script>

<style scoped lang="scss">
.create-comment {
	display: flex;
	padding: 5px 0;
}
.el-avatar {
	border-radius: 0;
	width: 30px;
	height: 30px;
	margin-right: 10px;
}
.main {
	display: flex;
	width: 100%;
	align-items: center;
	flex-direction: column;
	.el-button {
		width: 62px;
		height: 26px;
		border-radius: 2px;
		font-size: 12px;
		margin-top: 10px;
	}
}
</style>
